/**
 * 传输队列控制器 - 仅保存已完成和失败的传输记录
 * 客户端在传输完成/失败时上传记录到服务器
 */
const db = require('../config/database');
const logger = require('../config/logger');

/**
 * 保存传输任务（完成/失败）
 * POST /api/transfer-queue/save
 */
exports.saveTransferTask = async (req, res) => {
  try {
    const userId = req.user.id;
    const { client_id, task_id, type, file_name, local_path, remote_path, file_id, file_size, transferred, progress, speed, status, error, start_time, end_time } = req.body;

    // 验证必填字段
    if (!client_id || !task_id || !type || !file_name) {
      return res.status(400).json({
        success: false,
        message: '缺少必填字段'
      });
    }

    // 只保存已完成或失败的任务
    if (status !== 'completed' && status !== 'failed') {
      return res.status(400).json({
        success: false,
        message: '只能保存已完成或失败的任务'
      });
    }

    // 使用 INSERT ... ON DUPLICATE KEY UPDATE 避免重复
    const query = `
      INSERT INTO transfer_tasks (
        user_id, client_id, task_id, type, file_name, local_path, remote_path,
        file_id, file_size, transferred, progress, speed, status, error,
        start_time, end_time
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      ON DUPLICATE KEY UPDATE
        file_size = VALUES(file_size),
        transferred = VALUES(transferred),
        progress = VALUES(progress),
        speed = VALUES(speed),
        status = VALUES(status),
        error = VALUES(error),
        start_time = VALUES(start_time),
        end_time = VALUES(end_time),
        updated_at = CURRENT_TIMESTAMP
    `;

    const params = [
      userId,
      client_id,
      task_id,
      type,
      file_name,
      local_path || null,
      remote_path || null,
      file_id || null,
      file_size || 0,
      transferred || 0,
      progress || 0,
      speed || 0,
      status,
      error || null,
      start_time || null,
      end_time || null
    ];

    const [result] = await db.query(query, params);

    logger.info(`保存传输任务: user=${userId}, client=${client_id}, task=${task_id}, status=${status}, file=${file_name}`);

    res.json({
      success: true,
      message: '传输任务保存成功',
      data: {
        id: result.insertId
      }
    });
  } catch (error) {
    logger.error('保存传输任务失败:', error);
    res.status(500).json({
      success: false,
      message: '保存传输任务失败: ' + error.message
    });
  }
};

/**
 * 批量保存传输任务
 * POST /api/transfer-queue/batch-save
 */
exports.batchSaveTransferTasks = async (req, res) => {
  try {
    const userId = req.user.id;
    const { tasks } = req.body;

    if (!Array.isArray(tasks) || tasks.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请提供任务列表'
      });
    }

    // 过滤只保存完成/失败的任务
    const validTasks = tasks.filter(t => t.status === 'completed' || t.status === 'failed');

    if (validTasks.length === 0) {
      return res.json({
        success: true,
        message: '没有需要保存的任务',
        saved: 0
      });
    }

    // 批量插入
    const query = `
      INSERT INTO transfer_tasks (
        user_id, client_id, task_id, type, file_name, local_path, remote_path,
        file_id, file_size, transferred, progress, speed, status, error,
        start_time, end_time
      ) VALUES ?
      ON DUPLICATE KEY UPDATE
        file_size = VALUES(file_size),
        transferred = VALUES(transferred),
        progress = VALUES(progress),
        speed = VALUES(speed),
        status = VALUES(status),
        error = VALUES(error),
        end_time = VALUES(end_time),
        updated_at = CURRENT_TIMESTAMP
    `;

    const values = validTasks.map(task => [
      userId,
      task.client_id,
      task.task_id || task.id,
      task.type,
      task.file_name || task.fileName,
      task.local_path || task.localPath || null,
      task.remote_path || task.remotePath || null,
      task.file_id || task.fileId || null,
      task.file_size || task.fileSize || 0,
      task.transferred || 0,
      task.progress || 0,
      task.speed || 0,
      task.status,
      task.error || null,
      task.start_time || task.startTime || null,
      task.end_time || task.endTime || Date.now()
    ]);

    await db.query(query, [values]);

    logger.info(`批量保存传输任务: user=${userId}, count=${validTasks.length}`);

    res.json({
      success: true,
      message: `成功保存 ${validTasks.length} 个任务`,
      saved: validTasks.length
    });
  } catch (error) {
    logger.error('批量保存传输任务失败:', error);
    res.status(500).json({
      success: false,
      message: '批量保存传输任务失败: ' + error.message
    });
  }
};

/**
 * 获取传输任务列表
 * GET /api/transfer-queue/list
 */
exports.getTransferTasks = async (req, res) => {
  try {
    const userId = req.user.id;
    const { client_id, type, status, limit = 100, offset = 0 } = req.query;

    let query = `
      SELECT 
        id, client_id, task_id, type, file_name, local_path, remote_path,
        file_id, file_size, transferred, progress, speed, status, error,
        start_time, end_time, created_at, updated_at
      FROM transfer_tasks
      WHERE user_id = ?
    `;

    const params = [userId];

    // 客户端ID过滤
    if (client_id) {
      query += ' AND client_id = ?';
      params.push(client_id);
    }

    // 类型过滤
    if (type && (type === 'upload' || type === 'download')) {
      query += ' AND type = ?';
      params.push(type);
    }

    // 状态过滤
    if (status) {
      query += ' AND status = ?';
      params.push(status);
    }

    // 排序和分页
    query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
    params.push(parseInt(limit), parseInt(offset));

    const [tasks] = await db.query(query, params);

    // 获取总数
    let countQuery = 'SELECT COUNT(*) as total FROM transfer_tasks WHERE user_id = ?';
    const countParams = [userId];
    if (client_id) {
      countQuery += ' AND client_id = ?';
      countParams.push(client_id);
    }
    if (type) {
      countQuery += ' AND type = ?';
      countParams.push(type);
    }
    if (status) {
      countQuery += ' AND status = ?';
      countParams.push(status);
    }

    const [countResult] = await db.query(countQuery, countParams);
    const total = countResult[0].total;

    res.json({
      success: true,
      data: {
        tasks,
        total,
        limit: parseInt(limit),
        offset: parseInt(offset)
      }
    });
  } catch (error) {
    logger.error('获取传输任务列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取传输任务列表失败'
    });
  }
};

/**
 * 删除传输任务
 * DELETE /api/transfer-queue/:id
 */
exports.deleteTransferTask = async (req, res) => {
  try {
    const userId = req.user.id;
    const { id } = req.params;

    // 检查任务是否属于当前用户
    const [tasks] = await db.query(
      'SELECT id FROM transfer_tasks WHERE id = ? AND user_id = ?',
      [id, userId]
    );

    if (tasks.length === 0) {
      return res.status(404).json({
        success: false,
        message: '任务不存在或无权删除'
      });
    }

    // 删除任务
    await db.query('DELETE FROM transfer_tasks WHERE id = ?', [id]);

    logger.info(`删除传输任务: user=${userId}, id=${id}`);

    res.json({
      success: true,
      message: '任务删除成功'
    });
  } catch (error) {
    logger.error('删除传输任务失败:', error);
    res.status(500).json({
      success: false,
      message: '删除传输任务失败'
    });
  }
};

/**
 * 批量删除传输任务
 * POST /api/transfer-queue/batch-delete
 */
exports.batchDeleteTransferTasks = async (req, res) => {
  try {
    const userId = req.user.id;
    const { ids } = req.body;

    if (!Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请提供任务ID列表'
      });
    }

    // 只删除属于当前用户的任务
    const [result] = await db.query(
      'DELETE FROM transfer_tasks WHERE id IN (?) AND user_id = ?',
      [ids, userId]
    );

    logger.info(`批量删除传输任务: user=${userId}, count=${result.affectedRows}`);

    res.json({
      success: true,
      message: `成功删除 ${result.affectedRows} 个任务`,
      deleted: result.affectedRows
    });
  } catch (error) {
    logger.error('批量删除传输任务失败:', error);
    res.status(500).json({
      success: false,
      message: '批量删除传输任务失败'
    });
  }
};

/**
 * 清除已完成的任务
 * POST /api/transfer-queue/clear-completed
 */
exports.clearCompletedTasks = async (req, res) => {
  try {
    const userId = req.user.id;
    const { client_id } = req.body;

    let query = 'DELETE FROM transfer_tasks WHERE user_id = ? AND status = ?';
    const params = [userId, 'completed'];

    if (client_id) {
      query += ' AND client_id = ?';
      params.push(client_id);
    }

    const [result] = await db.query(query, params);

    logger.info(`清除已完成任务: user=${userId}, count=${result.affectedRows}`);

    res.json({
      success: true,
      message: `成功清除 ${result.affectedRows} 个已完成任务`,
      deleted: result.affectedRows
    });
  } catch (error) {
    logger.error('清除已完成任务失败:', error);
    res.status(500).json({
      success: false,
      message: '清除已完成任务失败'
    });
  }
};

/**
 * 获取传输统计
 * GET /api/transfer-queue/stats
 */
exports.getTransferStats = async (req, res) => {
  try {
    const userId = req.user.id;
    const { client_id } = req.query;

    let baseQuery = 'SELECT COUNT(*) as count, SUM(file_size) as total_size FROM transfer_tasks WHERE user_id = ?';
    const baseParams = [userId];

    if (client_id) {
      baseQuery += ' AND client_id = ?';
      baseParams.push(client_id);
    }

    // 已完成
    const [completed] = await db.query(baseQuery + ' AND status = ?', [...baseParams, 'completed']);
    
    // 失败
    const [failed] = await db.query(baseQuery + ' AND status = ?', [...baseParams, 'failed']);

    // 上传统计
    const [uploaded] = await db.query(
      baseQuery + ' AND type = ? AND status = ?',
      [...baseParams, 'upload', 'completed']
    );

    // 下载统计
    const [downloaded] = await db.query(
      baseQuery + ' AND type = ? AND status = ?',
      [...baseParams, 'download', 'completed']
    );

    res.json({
      success: true,
      data: {
        completed: {
          count: completed[0].count,
          total_size: completed[0].total_size || 0
        },
        failed: {
          count: failed[0].count,
          total_size: failed[0].total_size || 0
        },
        uploaded: {
          count: uploaded[0].count,
          total_size: uploaded[0].total_size || 0
        },
        downloaded: {
          count: downloaded[0].count,
          total_size: downloaded[0].total_size || 0
        }
      }
    });
  } catch (error) {
    logger.error('获取传输统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取传输统计失败'
    });
  }
};
